<template>
  <div class="meeting-unit-view">
    <el-form :model="queryParams" inline size="small">
      <el-form-item>
        <el-input
          v-model="queryParams.unitAllName"
          placeholder="请输入单位全称"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.unitForShort"
          placeholder="请输入单位简称"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="getInfo()">
          查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="reset" icon="RefreshRight">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <div class="flex justify-between items-center mb-4">
      <el-button
        type="primary"
        icon="Plus"
        size="small"
        @click="addUnitDialog.show(null)"
      >
        新增
      </el-button>
    </div>
    <Table
      ref="tableRef"
      :data="tableData"
      row-key="id"
      :select-column="false"
      lazy
      :load="getTreeInfo"
      :tree-props="{ children: 'list', hasChildren: 'isChild' }"
    >
      <TableColumn
        prop="unitAllName"
        label="单位全称"
        align="left"
        :min-width="getColumnWidth(tableData, 'unitAllName', 300)"
      />
      <TableColumn
        prop="unitForShort"
        label="单位简称"
        :min-width="getColumnWidth(tableData, 'unitForShort', 300)"
      />
      <TableColumn label="排序" prop="sort" :min-width="100" />
      <TableColumn label="类型" :min-width="100">
        <template #default="{ row }">
          <el-tag v-if="row.unitType === '1'" type="warning">单位</el-tag>
          <el-tag v-else type="success">科室</el-tag>
        </template>
      </TableColumn>
      <TableColumn label="操作" fixed="right" :min-width="230">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            :disabled="row.unitType === '2'"
            @click="addUnitDialog.show(null, row.id)"
          >
            新增
          </el-button>
          <el-button
            type="warning"
            size="small"
            @click="addUnitDialog.show(row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleClickDeleteButton(row)"
          >
            删除
          </el-button>
        </template>
      </TableColumn>
    </Table>
    <Pagination
      v-model:current-page="page.currentPage"
      v-model:page-size="page.pageSize"
      :total="page.total"
      @size-change="getInfo()"
      @current-change="getInfo()"
    />
    <AddUnitDialog ref="addUnitDialog" @update="getInfo()" />
  </div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, useTemplateRef } from 'vue'
import Table from '@/components/table/Table.vue'
import TableColumn from '@/components/table/TableColumn.vue'
import { deleteUnit, getUnitByLazy, getUnitByPage } from '@/api/sys/unit'
import AddUnitDialog from './AddUnitDialog.vue'
import { ElMessageBox } from 'element-plus'
import { PageParam } from '@/type'
import { getColumnWidth } from '@/plugins/util'
import Pagination, { PageType } from '@/components/Pagination.vue'
import { Message } from '@/hooks/message'

const addUnitDialog =
  useTemplateRef<InstanceType<typeof AddUnitDialog>>('addUnitDialog')
const tableRef = useTemplateRef<InstanceType<typeof Table>>('tableRef')

const queryParams = reactive({
  unitAllName: undefined,
  unitForShort: undefined,
})
const tableData = ref([])
const page = reactive<PageType>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
})

async function getTreeInfo(
  row?: any,
  treeNode?: unknown,
  resolve?: (data: any[]) => void,
) {
  if (row.type === 2) {
    resolve([])
    return
  }

  const postData: PageParam = {
    currentPage: 0,
    pageSize: 0,
    sort: [],
    query: {
      node: row.id,
    },
  }

  const { data } = await getUnitByLazy(postData)
  if (data.status === 200) {
    if (data.data.length !== 0) {
      resolve(data.data)
    }
  }
}

function reset() {
  Object.assign(queryParams, {
    unitAllName: undefined,
    unitForShort: undefined,
  })
  getInfo()
}

async function getInfo(node = 0) {
  const postData: PageParam = {
    currentPage: page.currentPage,
    pageSize: page.pageSize,
    sort: [],
    query: {
      node: node,
      unitAllName: queryParams.unitAllName,
      unitForShort: queryParams.unitForShort,
    },
  }

  const { data } = await getUnitByPage(postData)
  if (data.status === 200) {
    tableData.value = []
    // 由于懒加载，必须加延迟，否则可能数据不更新。
    await nextTick()
    page.currentPage = data.data.currentPage
    page.pageSize = data.data.pageSize
    page.total = data.data.totalCount
    tableData.value = data.data.data
  }
}

async function handleClickDeleteButton(row: any) {
  ElMessageBox.confirm(`确定删除 ${row.unitForShort} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(async () => {
      const { data } = await deleteUnit(row.id)
      if (data.status === 200) {
        Message({
          message: data.message,
          type: 'success',
        })
        await getInfo()
      }
    })
    .catch(() => {})
}

onMounted(() => {
  getInfo()
})
</script>

<style scoped></style>
